#import "VideoShowViewController.h"
#import "MyCollectionViewCell.h"
#import "VideoPlayingViewController.h"
#import "VideoViewController.h"
#import "NetManager.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "ShootVideoViewController.h"
#import "LoginViewController.h"
#import "UIButton+WebCache.h"

@interface VideoShowViewController () <UICollectionViewDelegateFlowLayout>
{
    NSMutableArray * _dataSource;
}
@end


@implementation VideoShowViewController
static NSString * const videoShowCellIdentifier = @"VideoShowCell";
#define SCREEN_SCALE_WIDTH [UIScreen mainScreen].bounds.size.width/320
#define SCREEN_SCALE_HEIGTH [UIScreen mainScreen].bounds.size.height/568

- (void)getData
{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:@1 forKey:@"page"];
    [NetManager POSTDataWithParams:nil withUrl:@"/index.php/appVideo/page" header:nil success:^(id object) {
        NSLog(@"%@",object);
        [_dataSource addObjectsFromArray:object];
        [self.MyCollectionView reloadData];
        [self.MyCollectionView.header endRefreshing];
    } withAnimation:YES connectionFail:^(NSError *error) {
        [self.MyCollectionView.header endRefreshing];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.MyCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
//    
//    // 马上进入刷新状态
//    [self.MyCollectionView.header beginRefreshing];
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataSource = [NSMutableArray array];
    [self getData];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.MyCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSource removeAllObjects];
        [self getData];
    }];
//    [[UINavigationBar appearance] setTintColor:[UIColor redColor]];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];

    UINavigationBar *bar = [UINavigationBar appearance];
    //设置显示的颜色
    bar.barTintColor = [UIColor colorWithWhite:0.122 alpha:1.000];
    //设置字体颜色
    bar.tintColor = [UIColor whiteColor];
    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    

    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back2016"]
                      forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backToPreView)
     forControlEvents:UIControlEventTouchUpInside];
    leftBtn.frame = CGRectMake(0, 0, 20, 20);

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"msg_icon"]
                       forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(messageHandler)
      forControlEvents:UIControlEventTouchUpInside];
    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    
    UISearchBar * seachBar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
    seachBar.backgroundColor=[UIColor clearColor];
    seachBar.placeholder = @"搜索";
    [seachBar setImage:[UIImage imageNamed:@"search_icon.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
//    UITextView * textField = [seachBar objectAtIndex:0];
//    textField.frame = CGRectMake(0 , 0, 100, 31);

    
    //self.navigationItem.titleView = seachBar;
    self.title = @"视频秀";
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.MyCollectionView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
//    [self.MyCollectionView setCollectionViewLayout:flowLayout];
    // Register cell classes
    
    [self.MyCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:videoShowCellIdentifier];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:videoShowCellIdentifier forIndexPath:indexPath];
    cell.priase.text = _dataSource[indexPath.row][@"love_cnt"];//[UIImage imageNamed:@"tmp_video_show.png"]
    [cell.imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,_dataSource[indexPath.row][@"img_path"]]] placeholderImage:[UIImage imageNamed:@"tmp_video_show.png"]];
    
    if ((![[_dataSource[indexPath.row] objectForKey:@"avatar"] isEqual:[NSNull null]])){
    if ([_dataSource[indexPath.row][@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
        [cell.ava setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"avatar"]]] placeholderImage:[UIImage imageNamed:@"tmp_video_show.png"]];
    }else{
        [cell.ava setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,_dataSource[indexPath.row][@"avatar"]]] placeholderImage:[UIImage imageNamed:@"tmp_video_show.png"]];
    }
    }
//    [cell.ava setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,_dataSource[indexPath.row][@"avatar"]]] placeholderImage:[UIImage imageNamed:@"tmp_video_show.png"]];
    cell.ava.backgroundColor = [UIColor lightGrayColor];
    cell.ava.layer.masksToBounds = YES;
//    [cell.avatar setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,_dataSource[indexPath.row][@"avatar"]]] forState:UIControlStateNormal placeholderImage:[UIImage new]];
    cell.avatar.layer.masksToBounds = YES;
    
    cell.backgroundColor = [UIColor whiteColor];
    
    
//    cell.backgroundColor = [UIColor redColor];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoPlayingViewController *vpc = [[VideoPlayingViewController alloc] init];
    vpc.videoID = _dataSource[indexPath.row][@"id"];
    [self.navigationController pushViewController:vpc animated:YES];
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(145 * SCREEN_SCALE_WIDTH, 244*SCREEN_SCALE_HEIGTH);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#warning backToPreView
- (void) backToPreView{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
/**
 *  录制视频
 */
- (void) messageHandler{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*  mp=[userDefaults objectForKey:@"mp"];
    if(!(mp&&mp.length>5)){
        LoginViewController *vc = [LoginViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    ShootVideoViewController * vc = [ShootVideoViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    //[self presentViewController:vc animated:YES completion:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
